package org.xfg.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.xfg.domain.strategy.repository.IStrategyRepository;
import org.xfg.domain.strategy.service.armory.IStrategyDispatch;
import org.xfg.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.xfg.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.xfg.types.common.Constants;

import javax.annotation.Resource;
import java.util.*;

/**
 * 权重抽奖责任链
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;
    @Resource
    private IStrategyDispatch strategyDispatch;
    public Long userScore = 0L;

    /**
     * 权重规则过滤链
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        // 没有规则不需要前置过滤
        if (null == ruleValue){
            return next().logic(userId, strategyId);
        }

        // 1. 根据用户ID查询用户抽奖消耗的积分值，本章节我们先写死为固定的值。后续需要从数据库中查询。
        // 4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
        Map<Long, String> analyticaValue = getAnalyticaValue(ruleValue);
        if (null == analyticaValue || analyticaValue.isEmpty()) return  null;
        // 2. 准换keys值, 默认排序
        ArrayList<Long> analyticalSortedKeys = new ArrayList<>(analyticaValue.keySet());
        Collections.sort(analyticalSortedKeys);

        // 3. 找出第一个符合条件的值
        Long nextValue = analyticalSortedKeys.stream()
                .sorted(Comparator.reverseOrder())
                .filter(temp -> userScore >= temp)
                .findFirst()
                .orElse(null);

        // 4.权重抽奖
        if (null != ruleValue && null != analyticaValue.get(nextValue)){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticaValue.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        // 5. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    private Map<Long,String> getAnalyticaValue(String ruleValue){
        Map<Long,String> res = new HashMap<>();
        //4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
        String[] split = ruleValue.split(Constants.SPACE);
        for (String temp : split) {
            if (temp == null || temp.isEmpty()){
                return res;
            }
            String[] parts = temp.split(Constants.COLON);
            if (parts.length != 2){
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + temp);
            }
            // 4000 -> 4000:102,103,104,105
            res.put(Long.parseLong(parts[0]),temp);
        }
        return res;
    }



    @Override
    protected String ruleModel() {
        return "rule_weight";
    }

}



















